package cn.edu.swu.miniwebsvr.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class HttpParser {

    public static Parameter parse(InputStream inputStream) throws IOException {
        Parameter parameter = new Parameter();
        //TODO：【222024321072046/马云山]
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(inputStream, StandardCharsets.UTF_8)
        );

        // 1. 解析请求行
        String requestLine = reader.readLine();
        if (requestLine == null || requestLine.isEmpty()) {
            throw new IOException("无效的请求行");
        }
        parseRequestLine(requestLine, parameter);

        // 2. 解析请求头
        String headerLine;
        while ((headerLine = reader.readLine()) != null && !headerLine.isEmpty()) {
            parseHeaderLine(headerLine, parameter);
        }

        // 3. 解析请求体（POST方法）
        if ("POST".equalsIgnoreCase(parameter.getMethod())) {
            String contentLengthStr = parameter.getHeaders().get("Content-Length");
            if (contentLengthStr != null && !contentLengthStr.isEmpty()) {
                int contentLength = Integer.parseInt(contentLengthStr);
                char[] bodyChars = new char[contentLength];
                reader.read(bodyChars, 0, contentLength);
                String body = new String(bodyChars);
                parseBodyParameters(body, parameter);
            }
        }

        return parameter;
        //TODO：【222024321072046/马云山]
    }

    private static void parseRequestLine(String requestLine, Parameter parameter) {
        String[] parts = requestLine.split("\\s+");
        if (parts.length < 3) {
            throw new IllegalArgumentException("无效的请求行格式: " + requestLine);
        }

        // 设置请求方法
        parameter.setMethod(parts[0]);

        // 解析URL和参数
        String url = parts[1];
        int queryIndex = url.indexOf('?');
        if (queryIndex != -1) {
            // 提取URL路径
            parameter.setUrl(url.substring(0, queryIndex));
            // 解析URL参数
            String queryParams = url.substring(queryIndex + 1);
            parseQueryParameters(queryParams, parameter);
        } else {
            parameter.setUrl(url);
        }
    }

    private static void parseHeaderLine(String headerLine, Parameter parameter) {
        int colonIndex = headerLine.indexOf(':');
        if (colonIndex == -1) {
            return; // 忽略无效头
        }
        String key = headerLine.substring(0, colonIndex).trim();
        String value = headerLine.substring(colonIndex + 1).trim();
        parameter.addHeader(key, value);
    }

    private static void parseQueryParameters(String query, Parameter parameter) {
        if (query.isEmpty()) {
            return;
        }
        String[] paramPairs = query.split("&");
        for (String pair : paramPairs) {
            String[] keyValue = pair.split("=", 2);
            String key = decode(keyValue[0]);
            String value = keyValue.length > 1 ? decode(keyValue[1]) : "";
            parameter.addUrlParam(key, value);
        }
    }

    private static void parseBodyParameters(String body, Parameter parameter) {
        if (body.isEmpty()) {
            return;
        }
        String[] paramPairs = body.split("&");
        for (String pair : paramPairs) {
            String[] keyValue = pair.split("=", 2);
            String key = decode(keyValue[0]);
            String value = keyValue.length > 1 ? decode(keyValue[1]) : "";
            parameter.addBodyParam(key, value);
        }
    }

    private static String decode(String value) {
        try {
            return URLDecoder.decode(value, StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            return value; // 解码失败时返回原始值
        }
    }
}